package cn.firecode.data_collect.filter;
import	java.awt.Desktop.Action;

import java.io.IOException;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import cn.firecode.data_collect.domain.entity.CollectUserT;
import cn.firecode.data_collect.utils.DataResponse;
import cn.firecode.data_collect.utils.JwtHelper;
import cn.firecode.data_collect.utils.ParameterRequestWrapper;
import cn.firecode.data_collect.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @author: yangfan
 * @Date: 2019/12/10
 * @Description:
 */
@Slf4j
public class JwtFilter implements Filter {

    @Autowired
    private RedisUtil redisUtil;

    private JwtHelper jwtHelper;
    private List<String> ignoreUrls = null;
    private static final org.springframework.util.PathMatcher pathMatcher = new AntPathMatcher();
    public JwtFilter(JwtHelper jwtHelper, String[] _ignoreUrls) {
        this.jwtHelper = jwtHelper;
        ignoreUrls = Arrays.asList(_ignoreUrls);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());
        ServletContext context = filterConfig.getServletContext();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
        redisUtil = ac.getBean(RedisUtil.class);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        System.out.println(httpRequest.toString());
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("UTF-8");
        //httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        if ("OPTIONS".equals(httpRequest.getMethod())) {
            httpResponse.setStatus(HttpStatus.NO_CONTENT.value()); // HttpStatus.SC_NO_CONTENT = 204
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Token");
            httpResponse.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE,PUT");
        }
        String spath = httpRequest.getServletPath();

        for(String url : ignoreUrls){
            if(pathMatcher.match(url, spath)){
                chain.doFilter(request, response);
                return;
            }
        }
        try {
            Map<String, Object>  token = jwtHelper.validateTokenAndGetClaims(httpRequest);
            if (token != null) {
                Integer userid = (Integer) token.get("userid");
                try {
                    CollectUserT currentUser = (CollectUserT) redisUtil.get("currentUser" + userid);
                    if(currentUser!=null){
                        Map paramter = new HashMap(16);
                        paramter.put("currentuser", userid);
                        ParameterRequestWrapper wrapper = new ParameterRequestWrapper(httpRequest, paramter);
                        chain.doFilter(wrapper, response);
//                        request.setAttribute("currentuser",userid);
//                        chain.doFilter(request, response);
                        return;
                    }else{
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
                        return;
                    }
                }catch (Exception e) {
                    httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
                    return;
                }
            }else{
                httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
                return;
            }
        }catch (Exception e) {
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
            return;
        }




//        try {
//            // 验证受保护的接口
//            for (String url : urls) {
//                if (pathMatcher.match(url, spath)) {
//                    Map<String, Object>  token = jwtHelper.validateTokenAndGetClaims(httpRequest);
//                    if (token != null) {
//                        Integer userid = (Integer) token.get("userid");
//                        try {
//                            CollectUserT currentUser = (CollectUserT) redisUtil.get("currentUser" + userid);
//                            if(currentUser!=null){
//                                chain.doFilter(request, response);
//                                return;
//                            }
//                        }catch (Exception e) {
//                            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
//                            return;
//                        }
//                    }else{
//                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
//                        return;
//                    }
//                }else{
//                    chain.doFilter(request, response);
//                    return;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
//        return;
    }

    @Override
    public void destroy() {

    }
}
